<?php

/**
 * @file
 * Drush integration for Coder module.
 */

/**
 * Implements hook_drush_command().
 */
function coder_drush_command() {
  $items['coder-format'] = array(
    'description' => dt('Re-format and rewrite code according Drupal coding standards.'),
    'arguments' => array(
      'path' => dt('The path of a file to reformat. Or the name of a directory to (recursively) reformat all contained files within.'),
    ),
    'options' => array(
      'undo' => dt('Restores already processed files from backups generated by Coder format. Automatically searches for the latest backup file ([filename].coder.orig) and each file is replaced with its original version.'),
    ),
    'examples' => array(
      'drush coder-format sites/all/modules/coder/coder.module' => 'Re-format coder.module according to Drupal coding standards.',
      'drush coder-format --undo sites/all/modules/coder/coder.module' => 'Restore coder.module from coder.module.coder.orig backup file (if existent).',
      'drush coder-format sites/all/modules/coder' => 'Recursively re-format Coder module files according to Drupal coding standards.',
      'drush coder-format --undo sites/all/modules/coder' => 'Recursively restore Coder module files from *.coder.orig backup files (if existent).',
    ),
  );
  return $items;
}

/**
 * Implementation of hook_drush_help().
 */
function coder_drush_help($section) {
  switch ($section) {
    case 'drush:coder-format':
      return dt('Re-format and rewrite code according Drupal coding standards.');
  }
}

/**
 * Drush command callback for coder-format.
 */
function drush_coder_format() {
  $path = drush_get_context('DRUSH_DRUPAL_ROOT');
  $path .= '/' . drupal_get_path('module', 'coder') . '/scripts/coder_format/coder_format.inc';
  require_once $path;

  $undo = drush_get_option('undo', FALSE);
  $files = func_get_args();
  $cwd = drush_get_context('DRUSH_OLDCWD');
  foreach ($files as $file) {
    // Additionally support relative paths.
    // Do this first to prevent typo disasters (e.g., $file == '/').
    if (is_dir($cwd . '/' . $file)) {
      coder_format_recursive($cwd . '/' . $file, $undo);
    }
    elseif (file_exists($cwd . '/' . $file)) {
      coder_format_file($cwd . '/' . $file, $undo);
    }
    // If argument is a directory, process it recursively.
    elseif (is_dir($file)) {
      coder_format_recursive($file, $undo);
    }
    else {
      coder_format_file($file, $undo);
    }
  }
}

